package ui;
import java.awt.*;

import javax.imageio.ImageIO;
import javax.swing.*;

import common.Author;
import common.Book;
import database.AuthorManager;
import database.BookManager;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class AddBookUI extends JFrame{
	
//

			private JTextField textName;
			private JTextField textPath;
			public JFileChooser chooser;
			public File file;
			private JTextField textFieldBookId;
			private ArrayList<Author> allAuthors=AuthorManager.getAllAuthors();
			private ArrayList<Author> selectedAuthors=new ArrayList<Author>();
			private ArrayList<String> allAuthorsString=new ArrayList<String>();
			private Book b;
			
			private JList listAuthors;
			
			public AddBookUI() {
				
			       Image image = null;
				try {
					image = ImageIO.read(new File("images\\body.jpg"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					this.setContentPane(new ImagePanel(image));
				
				addWindowListener(new WindowAdapter() {
					@Override
					public void windowClosing(WindowEvent arg0) {
						setVisible(false);
						MainMenuUI.X.initializeBooklist();
						MainMenuUI.X.setVisible(true);
					}
				});
				setBounds(new Rectangle(300, 200, 428, 447));
				setResizable(false);
				getContentPane().setLayout(null);
				
				MainMenuUI.X.setVisible(false);
				
				for(int i=0;i<allAuthors.size();i++)
				{
					String str=allAuthors.get(i).getName()+" "+allAuthors.get(i).getLastName();
					allAuthorsString.add(str);
				}
				
				JScrollPane scrollPane = new JScrollPane();
				scrollPane.setBounds(125, 206, 163, 128);
				getContentPane().add(scrollPane);
				
				listAuthors = new JList(allAuthorsString.toArray());
				scrollPane.setViewportView(listAuthors);
				
				listAuthors.setSelectionModel(new DefaultListSelectionModel() {
				    @Override
				    public void setSelectionInterval(int index0, int index1) {
				        if(super.isSelectedIndex(index0)) {
				            super.removeSelectionInterval(index0, index1);
				        }
				        else {
				            super.addSelectionInterval(index0, index1);
				        }
				    }
				});
				
				
				JLabel lblBookName = new JLabel("Book Name:");
				lblBookName.setFont(new Font("MV Boli", Font.BOLD, 12));
				lblBookName.setForeground(new Color(139, 69, 19));
				lblBookName.setBounds(10, 64, 105, 14);
				getContentPane().add(lblBookName);
				
				JLabel lblPath = new JLabel("Path:");
				lblPath.setFont(new Font("MV Boli", Font.BOLD, 12));
				lblPath.setForeground(new Color(139, 69, 19));
				lblPath.setBounds(10, 114, 46, 14);
				getContentPane().add(lblPath);
				
				textName = new JTextField();
				textName.setBounds(125, 61, 163, 20);
				getContentPane().add(textName);
				textName.setColumns(10);
				
				textPath = new JTextField();
				textPath.setBounds(125, 111, 163, 20);
				getContentPane().add(textPath);
				textPath.setColumns(10);
				
				JLabel lblAddBook = new JLabel("ADD BOOK");
				lblAddBook.setFont(new Font("MV Boli", Font.BOLD, 22));
				lblAddBook.setForeground(new Color(139, 69, 19));
				lblAddBook.setBounds(151, 11, 137, 24);
				getContentPane().add(lblAddBook);
				

				ImageIcon b1 = new ImageIcon("images\\browse.png");
		
				JButton btnBrowse = new JButton(b1);
				
				chooser= new JFileChooser("books");
				
	btnBrowse.setBorder(BorderFactory.createEmptyBorder());
				
				btnBrowse.addMouseListener(new MouseAdapter() {
					  public void mouseClicked(MouseEvent e) {
					
						Scanner s=null;
						 int r = chooser.showOpenDialog(new JFrame());
						    if (r == JFileChooser.APPROVE_OPTION) {
						      String name = chooser.getSelectedFile().getAbsolutePath();
						      textPath.setText(name);
						      file=chooser.getSelectedFile();}
						
					}
				});
				btnBrowse.setBounds(302, 110, 90, 23);
				getContentPane().add(btnBrowse);
				

				ImageIcon b2 = new ImageIcon("images\\add.png");
				
				
				
				JButton btnAdd = new JButton(b2);
				btnAdd.setBounds(248, 352, 68, 23);
                
				btnAdd.setBorder(BorderFactory.createEmptyBorder());
				
				btnAdd.addMouseListener(new MouseAdapter() {
					  @Override
					  public void mouseClicked(MouseEvent e) {

                    	//Book 
                    	b=new Book();
                    	int selectedIndexes[] = listAuthors.getSelectedIndices();
                    	
                    	for(int i=0;i<selectedIndexes.length;i++)
                    		selectedAuthors.add(allAuthors.get(selectedIndexes[i]));
                    	
    					if(check()==true){
    						b.setId((int)Integer.parseInt(textFieldBookId.getText()));
    						b.setPath(textPath.getText());
    						b.setTitle(textName.getText());
    						b.setAuthors(selectedAuthors);
    						boolean bb=BookManager.addBook(b);
    					if(bb){
    						System.out.println(bb);
    						 textName.setText("");
                			 textPath.setText("");
                			 textFieldBookId.setText("");
                			 listAuthors.clearSelection();
                			 b=new Book();
     						setVisible(false);
    						MainMenuUI.X.initializeBooklist();
    						MainMenuUI.X.setVisible(true);
    					infoBox("INFORMATION: Book Addition Sucseeded! ", "TITLE BAR MESSAGE");}
    					else{
    						infoBox("Warning: Book Addition Failed! ", "TITLE BAR MESSAGE");
    						}	
    					}
				}});
				getContentPane().add(btnAdd);
				

				ImageIcon b3 = new ImageIcon("images\\reset.png");
				
				
				JButton btnReset = new JButton(b3);
				btnReset.setBounds(151, 352, 68, 23);
                btnReset.setBorder(BorderFactory.createEmptyBorder());
				
				btnReset.addMouseListener(new MouseAdapter() {
					  @Override
					  public void mouseClicked(MouseEvent e) {
						  ResetFields();
					
					}	
				});
				getContentPane().add(btnReset);
				

				ImageIcon b4 = new ImageIcon("images\\back.png");
				
				JButton btnBack = new JButton(b4);
                btnBack.setBorder(BorderFactory.createEmptyBorder());
				
				btnBack.addMouseListener(new MouseAdapter() {
					  @Override
					  public void mouseClicked(MouseEvent e) {
						
					    setVisible(false);
						MainMenuUI.X.initializeBooklist();
						MainMenuUI.X.setVisible(true);
						
					}
				});
				btnBack.setBounds(47, 352, 68, 23);
				getContentPane().add(btnBack);
				
				JLabel lblId = new JLabel("ID:");
				lblId.setFont(new Font("MV Boli", Font.BOLD, 12));
				lblId.setForeground(new Color(139, 69, 19));
				lblId.setBounds(10, 159, 46, 14);
				getContentPane().add(lblId);
				
				textFieldBookId = new JTextField();
				textFieldBookId.setColumns(10);
				textFieldBookId.setBounds(125, 156, 163, 20);
				getContentPane().add(textFieldBookId);
				
				JLabel lblAuthors = new JLabel("Authors:");
				lblAuthors.setFont(new Font("MV Boli", Font.BOLD, 12));
				lblAuthors.setForeground(new Color(139, 69, 19));
				lblAuthors.setBounds(10, 207, 105, 14);
				getContentPane().add(lblAuthors);
				
				this.setVisible(true);
			}

	public JTextField getTextName() {
		return textName;
	}


	public void setTextName(JTextField textName) {
		this.textName = textName;
	}



	public JTextField getTextPath() {
		return textPath;
	}


	public void setTextPath(JTextField textPath) {
		this.textPath = textPath;
	}


	public JTextField getTextFieldBookId() {
		return textFieldBookId;
	}


	public void setTextFieldBookId(JTextField textFieldBookId) {
		this.textFieldBookId = textFieldBookId;
	}
	
	public static void infoBox(String infoMessage, String location)
	{
	    JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + location, JOptionPane.INFORMATION_MESSAGE);
	}
	
	public void ResetFields()
	{
		 textName.setText("");
		 textPath.setText("");
		 textFieldBookId.setText("");
		 listAuthors.clearSelection();
		 selectedAuthors.clear();
		 selectedAuthors=new ArrayList<Author>();
	}
		
public boolean check(){

	// check id is integer
	try{
		Integer.parseInt(textFieldBookId.getText());
	}
	catch(Exception e){
		infoBox("Warning: You have to insert numerical book id! ", "TITLE BAR MESSAGE");
		ResetFields();
		return false;
	}
	
	// if selected authors
	if(selectedAuthors.size()==0)
	{
		infoBox("Warning: You have to choose at least one author ", "TITLE BAR MESSAGE");
		ResetFields();
		return false;
	}
	
	//if id is empty
	if(getTextFieldBookId().getText().equals("")){
		ResetFields();
		infoBox("Warning: You have to insert numerical book id! ", "TITLE BAR MESSAGE");
		return false;
	}
	//if id already exists
    if(BookManager.getBookById(Integer.parseInt(getTextFieldBookId().getText()))!=null){
    	infoBox("Warning: Current book id already exists!", "TITLE BAR MESSAGE");
    	ResetFields();
	return false;}
	
	//if book path is empty
	if(getTextPath().getText().equals("")){
		infoBox("Warning: You have to insert book path! ", "TITLE BAR MESSAGE");
		ResetFields();
		return false;
	}
	//is book title is empty
	if(getTextName().getText().equals("")){
		infoBox("Warning: You have to insert book title! ", "TITLE BAR MESSAGE");
		ResetFields();
		return false;}
	
	return true;
    }
}